import { Player } from "../entity/player.entity";
import { User } from "../entity/user.entity";
import { UserDao } from "./user_dao";
import orm_util from "../utils/orm_util";
import { GlobalConfig } from "../../config/global/global_config";
import { Unit } from "../entity/unit";
import { Monster } from "../entity/monster";
import { Treasure } from "../entity/treasure.entity";
import { QualityType } from "../consts/quality_type";
import net_result from "../consts/net_result";

export class PlayerDao{
    public static ins() : PlayerDao{
        if (PlayerDao._ins == null){
            PlayerDao._ins = new PlayerDao();
        }
        return PlayerDao._ins;
    }

    private static _ins = null;


    public createPlayer(){
        return new Player();
    }


    findOne(){

    }

    async getRandomPlayer(userId){
        let userR=await orm_util.getRepository(User);
        let enemy:Player=null; 
        let enemyU=await userR.createQueryBuilder()
        .where("id!=:id")
        .setParameters({ id:userId })
        .orderBy("RAND()")
        .limit(1)
        .getOne()
        if(!enemyU){
            enemyU=await userR.findOne(userId);
        }
        enemyU.player.init();
        enemy=enemyU.player;
        enemy.name=enemyU.nickName||"";
        enemy.avatarUrl=enemyU.avatarUrl||"";
        return enemy;
    }

   
    async updateForBuyTreasure(player:Player,quality:QualityType){
        let playerRep=await orm_util.getRepository(Player);
        let t:Treasure= new Treasure();
        t.init(quality,player);
        (await player.treasures).push(t);
        await playerRep.save(player);
        return net_result.success(undefined,t);
    }
    

   async updateForFightOver(player:Unit,enemy:Unit){
        let playerRep=await orm_util.getRepository(Player);
        // let player=await playerRep.findOne(playerId);
        let p=<Player>player;
        let e=<Monster>enemy;
        if(!p.isDied){
            p.curExp+=e.exp;
            if(p.curExp>p.exp){
                p.level++;
                p.curExp-=p.exp;
            }
            p.money+=e.money;
        }
        else{
            p.curExp-=e.exp;
            if(p.curExp<0){
                if(p.level!==1){
                    p.level--;
                    p.curExp+=GlobalConfig.ins().player[p.level].exp;
                }
                else{
                    p.curExp=0;
                }
            }
        }
        p.init();
        // console.log(player);
        await playerRep.save(player);
         
    }
}